<template>
  <div ref="pieChart" style="width: 100%; height: 350px"></div>
</template>
  
  <script>
import * as echarts from "echarts";

export default {
  name: "PieChart",
  props: ["chartData"],
  watch: {
    chartData: {
      deep: true,
      handler(newData) {
        this.$nextTick(() => {
          this.renderChart(newData);
        });
      },
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.renderChart(this.chartData);
    });
  },
  methods: {
    renderChart(data) {
      const chartDom = this.$refs.pieChart;
      const myChart = echarts.init(chartDom);

      const option = {
        tooltip: {
          trigger: "item",
        },
        legend: {
          top: "5%",
          left: "center",
        },
        series: [
          {
            name: "分类统计",
            type: "pie",
            radius: ["40%", "70%"],
            avoidLabelOverlap: false,
            label: {
              show: true,
              position: "inside", // 标签显示在饼图外面
              formatter: ({ name, value }) => {
                return `${name}(${value}本)`; // 显示名称、数值
              },
            },
            emphasis: {
              label: {
                show: true,
                fontSize: "18",
                fontWeight: "bold",
              },
            },
            labelLine: {
              show: false,
            },
            data: data,
          },
        ],
      };

      myChart.setOption(option, true);
    },
  },
};
</script>